package com.hange.ymcc.mq;

import com.alibaba.fastjson.JSON;
import com.hange.ymcc.constant.Regexconstant;
import com.hange.ymcc.domain.MessageStation;
import com.hange.ymcc.dto.MessageStationDto;
import com.hange.ymcc.exception.BusinessException;
import com.hange.ymcc.exception.ErrorCode;
import com.hange.ymcc.service.IMessageStationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RocketMQMessageListener(
        topic = Regexconstant.ROCKETMQ_TOPIC_COURSE,
        selectorExpression = Regexconstant.ROCKETMQ_TAG_STATION,
        consumerGroup = "service-course-station-consumer")
public class MQStationConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageStationService messageStationService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            String jsonStrMessage = new String(messageExt.getBody(), "UTF-8");
            MessageStationDto messageStationDto = JSON.parseObject(jsonStrMessage, MessageStationDto.class);
            List<Long> userids = messageStationDto.getIds();

            userids.forEach(id -> {
                MessageStation messageStation = new MessageStation();
                BeanUtils.copyProperties(messageStationDto,messageStation);
                messageStation.setSendTime(new Date());
                messageStation.setUserId(id);
                messageStationService.insert(messageStation);

                log.info("站内推送消息消费结果成功");
            });

        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }

    }
}
